/*
 * @ModuleName: 功能模块名称
 * @author: 上海灿实工程设备-陈世亮
 * @Date: 2022-02-05 16:55:47
 * @FilePath: \electron_vue\src\background.js
 */
"use strict";

import { app, protocol, BrowserWindow, ipcMain, ipcRenderer } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import { autoUpdater } from "electron-updater";
import path from "path";
const isDevelopment = process.env.NODE_ENV !== "production";

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } }
]);

let win;
async function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      preload: path.join(__dirname, "preload.js")
    }
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol("app");
    // Load the index.html when not in development
    win.loadURL("app://./index.html");
  }
}

//监听应用关闭
app.on("window-all-closed", () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    app.quit();
  }
});

// 监听应用最小化
app.on("activate", () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

app.on("ready", async () => {
  createWindow();
});

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === "win32") {
    process.on("message", (data) => {
      if (data === "graceful-exit") {
        app.quit();
      }
    });
  } else {
    process.on("SIGTERM", () => {
      app.quit();
    });
  }
}

// 检查更新
ipcMain.on("update", () => {
  checkUpdate();
});

function sendUpdateMessage(text) {
  win.webContents.send("message", text);
}

function checkUpdate() {
  if (process.platform == "darwin") {
    autoUpdater.setFeedURL("http://127.0.0.1:8080"); //设置要检测更新的路径
  } else {
    autoUpdater.setFeedURL("http://127.0.0.1:8080");
  }

  //检测更新
  autoUpdater.checkForUpdates();

  let message = {
    error: "检查更新出错",
    checking: "正在检查更新……",
    updateAva: "检测到新版本，正在下载……",
    updateNotAva: "现在使用的就是最新版本，不用更新"
  };

  //监听'error'事件
  autoUpdater.on("error", (err) => {
    sendUpdateMessage(message.error);
  });

  autoUpdater.on("checking-for-update", function () {
    sendUpdateMessage(message.checking);
  });

  //监听'update-available'事件，发现有新版本时触发
  autoUpdater.on("update-available", () => {
    sendUpdateMessage(message.updateAva);
  });

  autoUpdater.on("update-not-available", function (info) {
    sendUpdateMessage(message.updateNotAva);
  });

  // 更新下载进度事件
  autoUpdater.on("download-progress", (progressObj) => {
    // console.log(progressObj);
    // win.webContents.send("downloadProgress", progressObj);
    // win.setProgressBar(progressObj.percent / 100);
    sendUpdateMessage(progressObj.percent / 100);
  });

  // 下载完成
  autoUpdater.on(
    "update-downloaded",
    (
      event,
      releaseNotes,
      releaseName,
      releaseDate,
      updateUrl,
      quitAndUpdate
    ) => {
      autoUpdater.quitAndInstall();
    }
  );
}
